package com.neo.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.neo.service.DjsBatchRedEnvelopService;
import com.neo.service.DjsProjectFileService;
import com.neo.service.DjsRecordFileService;
import com.neo.service.DjsUserFileService;
import com.neo.service.TransferProjectService;
import com.neo.service.TransferService;
import com.neo.service.TransferUserService;
import com.neo.util.DjsStringUtil;
import com.neo.util.ReadFromFile;

@Controller
public class DjsController {

	@Autowired
	private DjsRecordFileService djsRecordFileService;
	@Autowired
	private DjsProjectFileService djsProjectFileService;
	@Autowired
	private DjsUserFileService djsUserFileService;
	@Autowired
	private DjsBatchRedEnvelopService djsBatchRedEnvelopService;
	@Autowired
	private TransferService transferService;
	@Autowired
	private TransferProjectService transferProjectService;
	@Autowired
	private TransferUserService transferUserService;
	
    protected static Logger logger= LoggerFactory.getLogger(DjsController.class); 

	@RequestMapping("/transfer")
	@ResponseBody
	public String transfer(@RequestParam(value = "type", required = true, defaultValue = "") int type,
			@RequestParam(value = "batch", required = true, defaultValue = "") String batch,@RequestParam(value = "userAccountId", required = true, defaultValue = "") String userAccountId) throws Exception {

		if (batch.length() != 6) {
			return "批次为6位数字";
		}
		String fileName = null;
		switch (type) {
		case 1:
			fileName = djsUserFileService.generalFile(batch);
			break;
		case 2:
			fileName = djsProjectFileService.generalFile(batch);
			break;
		case 3:
			fileName = djsRecordFileService.generalFile(batch,userAccountId);
			break;
		case 4:
			fileName = djsBatchRedEnvelopService.generalFile(batch);
		default:
			break;
		}

		return fileName;
	}

	@RequestMapping(value = "/execute", method = RequestMethod.GET)
	@ResponseBody
	public String executeSql(HttpServletResponse res,
			@RequestParam(value = "type", required = true, defaultValue = "") String type) throws Exception {
		switch (type) {
			case "updateBolanMobile":
				transferService.updateBolanMobile();
				break;
			case "bondProjectToUserAccount":
				transferUserService.bondProjectToUserAccount();
				break;
			case "insertProject":
				//transferProjectService.insertProject();
				break;
			default:
				break;
		}
		return "success";
	}	
		
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	@ResponseBody
	public String download(HttpServletResponse res,
			@RequestParam(value = "filename", required = true, defaultValue = "") String fileName) {

		res.setHeader("content-type", "application/octet-stream");
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			os = res.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File(DjsStringUtil.FILE_PATH + fileName)));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "success";
	}
	
	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String upload(HttpServletResponse res) {
		return "upload";
	}
	
	
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,String> testUploadFile(HttpServletRequest req,
	      MultipartHttpServletRequest multiReq) {
		Map<String,String> result = new HashMap<>();

	    // 获取上传文件的路径
	    String uploadFilePath = multiReq.getFile("file1").getOriginalFilename();
	    if (uploadFilePath.length()<1){
			result.put("result","error");
			result.put("message","文件为空");
			return result;
		}
	    logger.info("uploadFlePath:" + uploadFilePath);
	    
	    FileInputStream fis = null;
	    try {
	      fis = (FileInputStream) multiReq.getFile("file1").getInputStream();
	      List<String> list =  ReadFromFile.readFileGBK(fis);
	      result = readFromList(uploadFilePath,list);
	    } catch (Exception e) {
	      e.printStackTrace();
	    } finally {
	      if (fis != null) {
	        try {
	          fis.close();
	        } catch (IOException e) {
	          e.printStackTrace();
	        }
	      }
	    }
	    return result;
	  }

	private Map<String,String> readFromList(String uploadFilePath, List<String> list) throws Exception {
		Map<String,String> result = new HashMap<>();
		if (uploadFilePath.indexOf("APPZX")>0) {
			//批量开户结果文件
			logger.info("批量开户结果文件" );
			djsUserFileService.readResFile(list);
		}else if (uploadFilePath.indexOf("BIDINRES")>0) {
			djsProjectFileService.readResFile(list);
		}else if (uploadFilePath.indexOf("BIDRESP")>0) {
			djsRecordFileService.readResFile(list);
		}else if (uploadFilePath.indexOf("TRQT") > 0){
			logger.info("批量发红包结果文件");
			djsBatchRedEnvelopService.readResFile(list);
		}
		return result;
	}
}
